package main

import (
	"fmt"
	"io/ioutil"
	"math/rand"
	"regexp"
	"strconv"
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type Exam struct {
	Id       int
	Question string
	Answer   string
}

func checkErr(e error) {
	if e != nil {
		panic(e)
	}
}

//import Multiple Choice
func importdb(file, collectionName string) {
	session, err := mgo.Dial("127.0.0.1") //连接数据库
	checkErr(err)
	defer session.Close()
	session.SetMode(mgo.Monotonic, true)
	db := session.DB("examgen")        //数据库名称
	collection := db.C(collectionName) //如果该集合已经存在的话，则直接返回

	dat, err := ioutil.ReadFile(file)
	checkErr(err)
	content := string(dat)
	r := regexp.MustCompile(`(?s)\d\.(.*?)\s参考答案：(.*?)\s解析：`)
	exams := r.FindAllStringSubmatch(content, -1)
	// 137
	// fmt.Println(len(exams))
	if len(exams) == 0 {
		return
	}
	// fmt.Println(len(exams[1]))
	// fmt.Println("题干:", exams[10][1])
	// fmt.Println("答案：", exams[10][2])
	for i := 0; i < len(exams); i++ {
		err := collection.Insert(&Exam{i, exams[i][1], exams[i][2]})
		checkErr(err)
	}
}
func exportdb(n int, collectionName string) []string {
	content := make([]string, 2)
	session, err := mgo.Dial("127.0.0.1") //连接数据库
	checkErr(err)
	defer session.Close()
	session.SetMode(mgo.Monotonic, true)
	db := session.DB("examgen")        //数据库名称
	collection := db.C(collectionName) //如果该集合已经存在的话，则直接返回
	r := rand.New(rand.NewSource(int64(time.Now().Second())))
	num, err := collection.Count()
	// fmt.Println(num)
	checkErr(err)
	for i := 0; i < n; i++ {
		result := Exam{}
		// fmt.Println(r.Intn(num))
		collection.Find(bson.M{"id": r.Intn(num)}).One(&result)
		content[0] += strconv.Itoa(i+1) + ". " + result.Question + "\n"
		content[1] += result.Answer + "  "
	}
	return content
}
func main() {
	// importdb("./单选题.txt", "multiple_choice")
	// importdb("./判断题.txt", "true_or_false")
	// importdb("./简答题.txt", "short_answer")
	content := exportdb(6, "multiple_choice")
	question := "培训测试卷\n一、单选题\n" + content[0]
	answer := "培训测试卷答案\n一、单选题\n" + content[1]
	content = exportdb(3, "true_or_false")
	question += "二、判断题\n" + content[0]
	answer += "\n二、判断题\n" + content[1]
	content = exportdb(1, "short_answer")
	question += "三、简答题\n" + content[0]
	answer += "\n三、简答题" + content[1]
	fmt.Println(question)
	fmt.Println(answer)
}
